package com.rmfyzxfw.caseprocess.util.sm4;

/**
 * Created by $(USER) on $(DATE)
 */



import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SM4Utils {


    public static String secretKey = "20EC2C063AB7CF64R2D04FF83A316915";
    public static boolean hexString = true;

    public SM4Utils() {
    }


    public static String encryptData_ECB(String plainText) {
        if (plainText == null || plainText.trim().length() == 0) {
            return plainText;
        }
        String oldParam = plainText;
        try {

            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_ENCRYPT;

            byte[] keyBytes;
            if (hexString) {
                keyBytes = Util.hexStringToBytes(secretKey);
            } else {
                keyBytes = Util.hexStringToBytes(secretKey);
            }

            SM4 sm4 = new SM4();
            sm4.sm4_setkey_enc(ctx, keyBytes);
            byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText.getBytes(StandardCharsets.UTF_8));
            return Util.byteToHex(encrypted);
        } catch (Exception e) {
            return oldParam;
        }
    }

    public static String decryptData_ECB(String cipherText) {
        if (cipherText == null || cipherText.trim().length() == 0) {
            return cipherText;
        }
        String oldParam = cipherText;
        try {
            byte[] encrypted = Util.hexToByte(cipherText);
            cipherText= Base64.encode(encrypted);
            if (cipherText != null && cipherText.trim().length() > 0) {
                Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                Matcher m = p.matcher(cipherText);
                cipherText = m.replaceAll("");
            }

            SM4_Context ctx = new SM4_Context();
            ctx.isPadding = true;
            ctx.mode = SM4.SM4_DECRYPT;

            byte[] keyBytes;
            if (hexString) {
                keyBytes = Util.hexStringToBytes(secretKey);
            } else {
                keyBytes = secretKey.getBytes();
            }

            SM4 sm4 = new SM4();
            sm4.sm4_setkey_dec(ctx, keyBytes);
            byte[] decrypted = sm4.sm4_crypt_ecb(ctx, Base64.decode(cipherText));
            String result = new String(decrypted, StandardCharsets.UTF_8);
            return result;
        } catch (Exception e) {
            return oldParam;
        }
    }

    public static void main(String[] args) {
        String content = "19025484515";
//        String s = encryptData_ECB(content);
//        System.out.println(s);
        System.out.println(encryptData_ECB(content));
    }

}
